﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;


public class ThreadingListWork
{
    public static List<InterfaceClass> worklist = new List<InterfaceClass>();
    private static Semaphore worklistSemaphore = new Semaphore(0, int.MaxValue);
    private static System.Threading.Thread workThread;
    private static bool keepWork = false;
    static ThreadingListWork()
    {

    }
    static public void Start()
    {
        workThread = new Thread(new ThreadStart(WorkThread));
        workThread.IsBackground = true;
        workThread.Priority = ThreadPriority.Lowest;
        keepWork = true;
        workThread.Start();
    }
    static public void Stop()
    {
        keepWork = false;
        worklistSemaphore.Release();
        workThread.Join();
        workThread.Abort();

    }
    static public void AddWork(InterfaceClass w)
    {
        worklistSemaphore.Release();
        lock (worklist)
        {
            worklist.Add(w);
        }
    }
    static private InterfaceClass GetWork()
    {
        worklistSemaphore.WaitOne();
        if (worklist.Count == 0) return null;
        lock (worklist)
        {
            InterfaceClass one = worklist[0];
            worklist.RemoveAt(0);
            return one;
        }
    }
    private static void WorkThread()
    {
        while (keepWork)
        {
            InterfaceClass one = GetWork();
            if (keepWork == false) return;
            if (one == null) continue;
            try
            {
                one.Work();
            }
            catch (Exception ee)
            {
                //Function.WriteFile("log.txt", DateTime.Now.ToString() + "   线程调用错误！" + ee.StackTrace + "\r\n", true);
            }
        }
    }
}

